const { http } = require("../modal/db.config");
const {
  getCurrentDateTime,
  getCurrentDateTimeObj,
} = require("../modal/time.config");
const dayjs = require("dayjs");

const resolveDataFun = (req, list) => {
  return new Promise((resolve, reject) => {
    const p = list.map(async (item, index) => {
      item.userInfo = await req.services.UserService.findById(item.userId);
      return item;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};
const resolveRecordFun = (req, userId, date) => {
  return new Promise((resolve, reject) => {
    const list = Array.from({ length: date }, (v, i) => i);
    const p = list.map(async (d, index) => {
      const time = dayjs().subtract(d, "day");
      // 获取年月日时分秒
      const year = time.year();
      const month = ("0" + (time.month() + 1)).slice(-2); // 月份是从0开始的，所以需要+1，并且补足两位
      const day = ("0" + time.date()).slice(-2);
      const newData = await req.services.HealthRecordsService.getList({
        where: {
          userId,
        },
        like: {
          create_time: `${year}-${month}-${day}`,
        },
      });
      let data = newData[0];
      if (!data) {
        data = {
          weight: 0,
          height: 0,
          blood_pressure: 0,
          blood_sugar: 0,
          pulse: 0,
          heart_rate: 0,
          calorie: 0,
          userId: userId,
          time: `${year}-${month}-${day}`,
        };
      } else {
        data = {
          weight: data.weight,
          height: data.height,
          blood_pressure: data.blood_pressure,
          blood_sugar: data.blood_sugar,
          pulse: data.pulse,
          heart_rate: data.heart_rate,
          calorie: data.calorie,
          userId: userId,
          time: `${year}-${month}-${day}`,
        };
      }
      return data;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};

exports.create = async (req, res) => {
  const body = req.body;
  const {
    weight,
    height,
    blood_pressure,
    blood_sugar,
    pulse,
    heart_rate,
    calorie,
  } = body;
  const user = await req.services.UserService.decodeToken();
  const data = {
    weight,
    height,
    blood_pressure,
    blood_sugar,
    pulse,
    heart_rate,
    calorie,
    userId: user.userId,
    create_time: getCurrentDateTime(),
    update_time: getCurrentDateTime(),
  };
  const { year, month, day } = getCurrentDateTimeObj();
  const hasData = await req.services.HealthRecordsService.getCount({
    where: { userId: user.userId },
    like: {
      create_time: `${year}-${month}-${day}`,
    },
  });
  if (hasData) {
    res.status(200).json({ data: "今日已记录", msg: "fail", code: 500 });
  } else {
    const newData = await req.services.HealthRecordsService.create(data);
    if (newData.affectedRows === 1) {
      res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
    } else {
      res
        .status(200)
        .json({ data: "系统错误，请重试", msg: "fail", code: 500 });
    }
  }
};

exports.list = async (req, res) => {
  const body = req.body;
  const { userId, page, pageSize } = body;
  let newData = await req.services.HealthRecordsService.getList({
    where: {
      userId,
    },
    page,
    pageSize,
  });

  let count = await req.services.HealthRecordsService.getCount({
    where: {
      userId,
    },
  });

  const result = await resolveDataFun(req, newData);

  res.status(200).json({
    data: { list: result, total: count },
    msg: "success",
    code: 200,
  });
};

exports.update = async (req, res) => {
  const body = req.body;
  const {
    weight,
    height,
    blood_pressure,
    blood_sugar,
    pulse,
    heart_rate,
    calorie,
    id,
  } = body;
  const update_time = getCurrentDateTime();
  const data = {
    weight,
    height,
    blood_pressure,
    blood_sugar,
    pulse,
    heart_rate,
    calorie,
    update_time,
  };
  const newData = await req.services.HealthRecordsService.update(data, {
    id,
  });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.HealthRecordsService.findById(id);
  const result = await resolveDataFun(req, [newData]);
  if (newData) {
    res.status(200).json({ data: result[0], msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无此人", msg: "fail", code: 400 });
  }
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.HealthRecordsService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无此人", msg: "fail", code: 400 });
  }
};

exports.getRecordListByType = async (req, res) => {
  const body = req.body;
  const { date = 7, userId } = body;
  const user = await req.services.UserService.decodeToken();
  const _userId = user.role === "user" ? user.userId : userId;
  const newData = await resolveRecordFun(req, _userId, date);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: [], msg: "success", code: 200 });
  }
  // weight, blood_pressure, heart_rate, calorie
};
